package com.eptok.weixin.action;


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.eptok.weixin.util.WxCooikeManager;

import hikefa.core.remote.client.RemoteCall;
import hikefa.core.util.StringUtil;
import yspay.express.bean.Result;
import yspos.cpfs.entity.DataDict;
import yspos.cpfs.express.entity.ExpBizMerchant;
import yspos.cpfs.express.entity.ExpExpressCompany;
import yspos.cpfs.express.entity.ExpExpressMerchant;
import yspos.cpfs.express.entity.ExpUserinfo;
import yspos.cpfs.express.entity.Query;
import yspos.cpfs.remoteserver.iface.IExpressService;
import yspos.cpfs.remoteserver.iface.ITradeService;
import yspos.cpfs.remoteserver.iface.YsServerUtil;
import yspos.remoteserver.iface.IYsServer;
import yspos.trade.bean.cust.UserInfo;

@Controller
@RequestMapping("/weixin/user")
public class MerchantController  extends BaseDispatchAction{
	
	private IExpressService expressServer = (IExpressService) RemoteCall.getRemoteObject(IExpressService.class);
	private IYsServer ysServer = (IYsServer) RemoteCall.getRemoteObject(IYsServer.class);
	private ITradeService tradeService = (ITradeService) RemoteCall.getRemoteObject(ITradeService.class);
	
	private static final String dataType = "OPEN_MERCHANT";
	
	/**
	 * 判断是否有权开户
	 */
	@RequestMapping(value = { "/checkAutho.do" })    
	@ResponseBody
	public Result checkAutho(HttpServletRequest request, HttpServletResponse response) 
	{
		ExpUserinfo user = WxCooikeManager.getUser(request);
		try {
			DataDict data = tradeService.dataDictLoad(dataType,user.getPhone());
			if(null == data)
			{
				return Result.init("1", "无权限");
			}else
			{
				return Result.init("0", "ok");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Result.init("1", "错误："+e.getMessage());
		}
	}
	
	/*
	 * 判断重复
	 */
	@RequestMapping(value = { "/checkRepeat.do" })    
	@ResponseBody
	public Result checkRepeat(HttpServletRequest request, HttpServletResponse response,String phone) 
	{
		ExpUserinfo user = WxCooikeManager.getUser(request);
		ExpBizMerchant merc = expressServer.getBizMerchantByNo("BM"+phone);
		if(null == merc)
		{
			
		}else
		{
			if("01".equals(merc.getState()) && user.getPhone().equals(merc.getBizContactPhone()))//如果开户失败 并且开户人和操作人是同一人
			{
				return Result.init("2", "该商户上次一开户未完成,点击确定重新开户",merc.getMercNo());
			}else
			{
				return Result.init("1", "该手机已开户");
			}
		}
		
		ExpExpressMerchant merc2 = expressServer.getExpressMerchantByNo("EM"+phone);
		if(null == merc2)
		{
			return Result.init("0", "ok");
		}else
		{
			if("01".equals(merc2.getState()) && user.getPhone().equals(merc2.getBizContactPhone()))//如果开户失败 并且开户人和操作人是同一人
			{
				return Result.init("2", "该商户上次一开户未完成,点击确定重新开户",merc2.getMercNo());
			}else
			{
				return Result.init("1", "该手机已开户");
			}
		}
		
	}
	
	/******************************************快递商户*******************************************************/
	/*
	 * 跳转至：企业商户开户
	 */
	@RequestMapping(value = { "/toBizMerchantOpen.do" })    
	public ModelAndView toOpenBizMerchant(HttpServletRequest request, HttpServletResponse response) 
	{
		ExpUserinfo user = WxCooikeManager.getUser(request);
		DataDict data = tradeService.dataDictLoad(dataType,user.getPhone());
		if(null == data || StringUtil.isEmpty(data.getDescription()))
		{
			return toFail(request, "1", "您无权开户");
		}
		//判断机构号填写是否正确
		String orgName = ysServer.getOrgNameByOrgNo(data.getDescription());
		if(StringUtil.isEmpty(orgName))
		{
			return toFail(request, "1", "机构号填写错误，无法开户");
		}
		
		request.setAttribute("orgNo", data.getDescription());
		request.setAttribute("provjson", YsServerUtil.getProvJson());//所有的省全部加进去
		request.setAttribute("cityjson", YsServerUtil.getCityJson());//所有的市全部加进去

		return new ModelAndView(PATH+"/merchant/bizMerchantOpen");
	}
	
	
	
	/*
	 * 企业商户开户
	 */
	@RequestMapping(value = { "/bizMerchantOpen.do" })    
	public ModelAndView bizMerchantOpen(HttpServletRequest request, HttpServletResponse response,ExpBizMerchant bean) 
	{
		String mercNo = "";
		try {
			if(!StringUtil.isEmpty(bean.getMercNo()))//重新开户
			{
				mercNo = bean.getMercNo();
				ExpBizMerchant merc = expressServer.getBizMerchantByNo(mercNo);
				if(merc == null)
				{
					return toFail(request, "1", "开户失败：未找到该商户("+bean.getMercNo()+")");
				}
				if(!"01".equals(merc.getState()))
				{
					return toFail(request, "1", "操作失败：该商户无需重新开户");
				}
				expressServer.openAccBizMerchant(merc);
			}else
			{
				//判断重复
				ExpBizMerchant merc = expressServer.getBizMerchantByNo("BM"+bean.getContactPhone());
				if(null != merc)
				{
					return toFail(request, "1", "商户号重复");
				}
				
				/*判断代理商户是否存在*/
				if(!StringUtil.isEmpty(bean.getAgentNo()))
				{
					UserInfo m = ysServer.getUserInfoByUserCode(bean.getAgentNo());
					if(null == m )
					{
						toFail(request, "1", "代理商户号填写错误");
					}
				}
				
				
				ExpUserinfo user = WxCooikeManager.getUser(request);
				String orgName = ysServer.getOrgNameByOrgNo(bean.getOrgNo());
				if(StringUtil.isEmpty(orgName))
				{
					return toFail(request, "1", "无法获取机构名称（"+bean.getOrgName()+"）");
				}
				
				if(!StringUtil.isEmpty(bean.getMercBillSign()) && "on".equals(bean.getMercBillSign())) 
				{
					bean.setMercBillSign("ON");
				}else
				{
					bean.setMercBillSign("OFF");
				}
				
				bean.setOrgName(orgName);
				bean.setBizContact(user.getName());
				bean.setBizContactPhone(user.getPhone());
				bean.setPayeeProvinceName(YsServerUtil.getAreaName(bean.getPayeeProvinceCode()));
				bean.setPayeeCityName(YsServerUtil.getAreaName(bean.getPayeeCityCode()));
				ExpBizMerchant ret = expressServer.saveAndOpenAccBizMerchant(bean);
				mercNo = ret.getMercNo();
			}
			return toSuccess(request, "0", "开户完成，您的商户号是："+mercNo+"<br>"+"密码是商户号后6位，请牢记");
			
		} catch (Exception e) {
			return toFail(request, "1", "开户失败："+e.getMessage());
		}
		
		
	}
	
	/******************************************快递商户*******************************************************/
	/*
	 * 跳转至：企业商户开户
	 */
	@RequestMapping(value = { "/toExpMerchantOpen.do" })    
	public ModelAndView toExpMerchantOpen(HttpServletRequest request, HttpServletResponse response) 
	{
		ExpUserinfo user = WxCooikeManager.getUser(request);
		DataDict data = tradeService.dataDictLoad(dataType,user.getPhone());
		if(null == data || StringUtil.isEmpty(data.getDescription()))
		{
			return toFail(request, "1", "您无权开户");
		}
		
		//判断机构号填写是否正确
		String orgName = ysServer.getOrgNameByOrgNo(data.getDescription());
		if(StringUtil.isEmpty(orgName))
		{
			return toFail(request, "1", "机构号填写错误，无发开户");
		}
		
		request.setAttribute("orgNo", data.getDescription());
		request.setAttribute("provjson", YsServerUtil.getProvJson());//所有的省全部加进去
		request.setAttribute("cityjson", YsServerUtil.getCityJson());//所有的市全部加进去
		
		List<ExpExpressCompany> listComys = expressServer.listExpressCompany(new Query());
		request.setAttribute("listComys", listComys);
		
		return new ModelAndView(PATH+"/merchant/expMerchantOpen");
	}

	
	/*
	 * 快递商户开户
	 */
	@RequestMapping(value = { "/expMerchantOpen.do" })    
	public ModelAndView expMerchantOpen(HttpServletRequest request, HttpServletResponse response,ExpExpressMerchant bean) 
	{
		String mercNo = "";
		try {
			if(!StringUtil.isEmpty(bean.getMercNo()))//重新开户
			{
				mercNo = bean.getMercNo();
				ExpExpressMerchant merc = expressServer.getExpressMerchantByNo(bean.getMercNo());
				if(merc == null)
				{
					return toFail(request, "1", "开户失败：未找到该商户("+bean.getMercNo()+")");
				}
				if(!"01".equals(merc.getState()))
				{
					return toFail(request, "1", "操作失败：该商户无需重新开户");
				}
				expressServer.openAccExpMerchant(merc);
			}else
			{
				//判断重复
				ExpExpressMerchant merc = expressServer.getExpressMerchantByNo("EM"+bean.getContactPhone());
				if(null != merc)
				{
					return toFail(request, "1", "商户号重复");
				}
				
				/*判断代理商户是否存在*/
				if(!StringUtil.isEmpty(bean.getAgentNo()))
				{
					UserInfo m = ysServer.getUserInfoByUserCode(bean.getAgentNo());
					if(null == m )
					{
						toFail(request, "1", "代理商户号填写错误");
					}
				}
				
				ExpUserinfo user = WxCooikeManager.getUser(request);
				String orgName = ysServer.getOrgNameByOrgNo(bean.getOrgNo());
				if(StringUtil.isEmpty(orgName))
				{
					return toFail(request, "1", "无法获取机构名称（"+bean.getOrgName()+"）");
				}
				bean.setOrgName(orgName);
				bean.setBizContact(user.getName());
				bean.setBizContactPhone(user.getPhone());
				
				bean.setPayeeProvinceName(YsServerUtil.getAreaName(bean.getPayeeProvinceCode()));
				bean.setPayeeCityName(YsServerUtil.getAreaName(bean.getPayeeCityCode()));
				
				ExpExpressMerchant ret = expressServer.saveAndOpenAccExpMerchant(bean);
				mercNo = ret.getMercNo();
			}
			return toSuccess(request, "0", "开户完成，您的商户号是："+mercNo+"<br>"+"密码是商户号后6位，请牢记");
			
		} catch (Exception e) {
			return toFail(request, "1", "开户失败："+e.getMessage());
		}
		
		
	}
	
}
